/**********************************************************************
 * 
 * Name: RejectedGoodApproveREST
 * Object: ReturnOrder__c
 * Purpose: Upsert ReturnOrder__c from NC
 * Requirement:
 * Author: kittylau (382376269@qq.com)
 * Create Date: 2017-01-17
 * Modify History: 
 * 
 * Url: /services/apexrest/CRM/rejectedGoodApproveREST
 * 接收的Json数据格式:
   {
        "data":{"ts":"最后更新时间"}
   }
  返回的Json数据格式：
  {
    "result":"0 OR 1 , 1表示成功，0表示失败", 
    "result_msg":"成功为取得的数据条数，失败时为失败原因信息",
    "data":[{
        //CRM字段
        "id":"退货申请单Id",
        "return_code":"退货单号",
        "dept_manager":"部门经理",
        "finance":"财务部经理",
        "capproveid":"子公司总经理(审批人)",
        "applicant":"申请人",
        "contact":"联系人",
        "contact_dept":"联系人部门",
        "contact_phone":"联系人电话",
        "contact_post":"联系人职务",
        "contact_date":"联系日期(日期)",
        "returnreason":"退货原因",
        "nreturnfee":"客户退回运费",
        "return_reason_other":"其他原因说明",
        "nnum":"退货数量",
        "is_return_invoice":"是否退发票",
        "approved_date":"审核通过时间(日期时间)",
        "coperatorid":"制单人",
        //NC字段
        "dbillcode":"来源出库订单号",
        "cgeneralhid":"来源出库订表头pk",
        "cgeneralbid":"来源出库订表体pk",
        "corpcode":"公司编码",
        "corpname":"公司名称",
        "custcode":"客户编号",
        "custname":"客户名称",
        "dbilldate":"制单日期",
        "invname":"产品名称",
        "invcode":"产品代码",
        "invtype":"产品型号",
        "invdm":"助记码(产品代码)",
        "transfer_number":"调拨单号",
        "invoice_number":"发票号",
        "ckcode":"仓库代码", 
        "ckname":"仓库名称", 
        "vbatchcode":"批次号"
    },{...}]
  }
*************************************************************************/
@RestResource(urlMapping='/CRM/rejectedGoodApproveREST/*')
global without sharing class RejectedGoodApproveREST {
    @HttpPost
    global static RestReturnMessage getApprovedReturnOrder(Map<String,String> data) {
        RestReturnMessage msg = null;
        if(data != null && data.containsKey('ts')){
            try{
                Datetime dt = Datetime.valueOf(data.get('ts'));
                try{
                    msg = getReturnOrderApprove(dt);
                }
                catch(Exception ex){
                    System.debug('*** 错误信息: ' + ex.getMessage() + ' - ' + ex.getStackTraceString());
                    msg = Utils.getRestReturnMessage(false,ex.getMessage()+ ' - ' + ex.getStackTraceString());
                }
            }catch(Exception ex){
                System.debug('*** 错误信息: ' + ex.getMessage() + ' - ' + ex.getStackTraceString());
                msg = Utils.getRestReturnMessage(false,'错误的ts参数值,需要日期时间格式(yyyy-MM-dd HH:mm:ss)');
            }
        }else{
            System.debug('*** 错误信息: 参数错误');
            msg = Utils.getRestReturnMessage(false,'参数错误');
        }
        return msg;
    }

    /*
        描述：以上次读取时的最大时间为基准，读取最新审核过的数据
        参数：ts - 上次读取时的最大时间
    */
    global static RestReturnMessage getReturnOrderApprove (Datetime ts) {
        Datetime maxTs = Datetime.valueOf(Utils.MIN_DATE_TIME);
        System.debug(LoggingLevel.INFO, '*** ESB最后保存的更新时间: ' + ts);

        //保存退货申请单
        List<ReturnOrder__c> roList = [SELECT Id,Name,Applicant__r.Name,DeptManager__r.Name,Finance__r.Name,
                    Product__r.Name,Product__r.NCCode__c,Product__r.Model__c,Product__r.Spec__c,
                    Product__r.SerialNo__c,TransferNumber__c,InvoiceNumber__c,ZiManager__r.Name,
                    Contact__r.Name,ContactDept__c,ContactPhone__c,ContactPost__c,ContactDate__c,
                    Return_Reason__c,Other_Reasons__c,MakeDate__c,Return_Number__c,Is_Return_Invoice__c,
                    Approved_Date__c,CreatedBy.Name,
                    ExWarehouse__r.Name,ExWarehouse__r.ckname__c,ExWarehouse__r.corpcode__c,
                    ExWarehouse__r.corpname__c,ExWarehouse__r.custcode__c,ExWarehouse__r.custname__c, 
                    ExWarehouse__r.cgeneralhid__c  
                FROM ReturnOrder__c  
                WHERE Approve_Status__c='审批通过' AND Approved_Date__c > :ts];

        //记录出库单号-产品编号和出库明细Id号的对应关系
        Map<String,String> mapExws = new Map<String,String>();
        //记录出库单号-产品编号和批次号的对应关系
        Map<String,String> mapBats = new Map<String,String>();
        String key = '';
        for(ReturnOrder__c ro : roList){
            key = ro.ExWarehouse__r.Name;
            if(!mapExws.containsKey(key)){
                mapExws.put(key, '');
            }
        }
        List<ExWarehouse_Detail__c> opList = [SELECT Id,Name,outcode__c,invcode__c,vbatchcode__c FROM ExWarehouse_Detail__c WHERE outcode__c IN :mapExws.keySet()];
        mapExws.clear();
        for(ExWarehouse_Detail__c op : opList){
            key = op.outcode__c + '-' + op.invcode__c;
            if(!mapExws.containsKey(key)){
                mapExws.put(key, op.Name);
            }
            if(!mapBats.containsKey(key)){
                mapBats.put(key, op.vbatchcode__c);
            }
        }
        //保存要返回给调用者的数据集合
        List<Map<String,String>> datas = new List<Map<String,String>>();
        for(ReturnOrder__c ro : roList){
            Map<String,String> data = new Map<String,String>();
            //CRM数据
            data.put('id', ro.Id);//退货单id
            data.put('return_code', ro.Name);//退货单号
            data.put('dept_manager', ro.DeptManager__r.Name);//部门经理
            data.put('finance', ro.Finance__r.Name);//财务部
            data.put('capproveid', ro.ZiManager__r.Name);//子公司总经理-审核人
            data.put('transfer_number', ro.TransferNumber__c);//调拨单号
            data.put('invoice_number', ro.InvoiceNumber__c);//发票号
            data.put('applicant', ro.Applicant__r.Name);//申请人
            data.put('contact', ro.Contact__r.Name);//联系人
            data.put('contact_dept', ro.ContactDept__c);//联系人部门
            data.put('contact_phone', ro.ContactPhone__c);//联系人电话
            data.put('contact_post', ro.ContactPost__c);//联系人职务
            data.put('contact_date', ro.ContactDate__c!=null?ro.ContactDate__c.format():'');//联系日期(日期)
            data.put('returnreason', ro.Return_Reason__c);//退货原因
            data.put('nreturnfee','0');//客户退回运费
            data.put('return_reason_other', ro.Other_Reasons__c);//其他原因说明
            data.put('nnum', ro.Return_Number__c!=null?ro.Return_Number__c.format():'0');//退货数量
            data.put('is_return_invoice', ro.Is_Return_Invoice__c?'Y':'N');//是否退发票
            data.put('approved_date', ro.Approved_Date__c!=null?ro.Approved_Date__c.format():'');//审核通过时间(日期时间)
            data.put('coperatorid',ro.CreatedBy.Name);//制单人
            data.put('ckcode','');//仓库
            data.put('ckname',ro.ExWarehouse__r.ckname__c);//仓库
            data.put('ctransmodeid','');//运输方式
            //NC数据
            data.put('invname', ro.Product__r.Name);//产品名称
            data.put('invcode', ro.Product__r.NCCode__c);//产品代码
            data.put('invtype', ro.Product__r.Model__c);//产品型号
            data.put('invspec', ro.Product__r.Spec__c);//产品规格
            data.put('invdm', ro.Product__r.SerialNo__c);//助记码(产品代码)
            data.put('corpcode', ro.ExWarehouse__r.corpcode__c);//公司编号
            data.put('corpname', ro.ExWarehouse__r.corpname__c);//公司名称
            data.put('custcode', ro.ExWarehouse__r.custcode__c);//客户编号
            data.put('custname', ro.ExWarehouse__r.custname__c);//客户名称
            data.put('dbilldate', ro.MakeDate__c!=null?ro.MakeDate__c.format():'');//制单日期
            data.put('dbillcode', ro.ExWarehouse__r.Name);//来源出库订单号
            data.put('cgeneralhid', ro.ExWarehouse__r.cgeneralhid__c);//来源出库订表头pk
            key = ro.ExWarehouse__r.Name + '-' + ro.Product__r.NCCode__c;
            data.put('cgeneralbid', mapExws.containsKey(key)?mapExws.get(key):'');//来源出库订表体pk
            data.put('vbatchcode', mapBats.containsKey(key)?mapBats.get(key):'');//批次号
            data.put('ts', ro.Approved_Date__c!=null?ro.Approved_Date__c.format():'');//最后更新时间
            data.put('opertype','1');//操作类型
            datas.add(data);
        }
        return Utils.getRestReturnMessage(true,'成功查询到' + roList.size() + '条记录',datas);
    }
}